import axios from 'axios'
import obj from '@/common/config.js'
// 获取对应的cookie值
import {
	getCookieName
} from '@/utils/index.js'
const service = axios.create({
	// withCredentials: true,
	crossDomain: true,
	baseURL: obj.baseUrl,
	timeout: 10000
})
axios.islogin = false
// request拦截器,在请求之前做一些处理
service.interceptors.request.use(
	config => {
		// config.headers['Terminal-Type'] = 'app'
		// const methodType = config.method

		config.url = encodeURI(`${config.url}`)

		console.log(config)
		return config
	}
)

// 配置成功后的拦截器
service.interceptors.response.use(
	res => {
		const response = res.data
		if (response && response.code !== 200) {

			uni.showToast({
				title: `${response.msg || ''}`,
				icon: 'none',
				duration: 2000
			})

			return Promise.reject(response)
		} else {
			return Promise.resolve(response)
		}
	},
	async (error) => {
		if (error.response && error.response.status === 401) {

			if (axios.islogin) {
				return false
			}
			axios.islogin = true
			uni.removeStorageSync('user_token')
			// 原先为uni.redirectTo(OBJECT) 被拦截后 无法使用uni.navigateBack()返回上一级
			// #ifdef H5
			axios.islogin = false
			// console.log('进入到拦截==')
			uni.navigateTo({
				url: '/subPages/login/index'
			})
			// #endif

		} else {
			uni.showToast({
				title: `${error.message}`,
				icon: 'none',
				duration: 2000
			})
		}
	})

axios.defaults.adapter = function(config) { // 自己定义个适配器，用来适配uniapp的语法
	return new Promise((resolve, reject) => {
		var settle = require('axios/lib/core/settle')
		var buildURL = require('axios/lib/helpers/buildURL')
		uni.request({
			method: config.method.toUpperCase(),
			url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
			header: config.headers,
			data: config.data,
			dataType: config.dataType,
			responseType: config.responseType,
			sslVerify: config.sslVerify,
			complete: function complete(response) {
				// console.log('执行完成：', response)
				response = {
					data: response.data,
					status: response.statusCode,
					errMsg: response.errMsg,
					header: response.header,
					config: config
				}

				settle(resolve, reject, response)
			}
		})
	})
}

 
export default service
